import { delayNavigateTo, getCurrentPage } from '@/utils/navigator';
import type { ICategoryStateRequest } from '@/typings/api';
import type { IProduct } from '@/typings/interface';
import { queryProductById } from '@/api/category';

type CategoryState = ICategoryStateRequest;

export const useCategory = defineStore('category', () => {
  let end = ref(false); // 接口无更多数据
  let products = ref<IProduct[]>([]); // 分类课程列表初始数组
  let categoryState = ref<CategoryState>({
    page:0,
    size:0,
    orderType:"new"
  })!;

  async function init(_categoryState: Partial<CategoryState>) {
    // @ts-expect-error 入参属性可选导致不匹配
    categoryState.value = _categoryState;

    // 拿到当前页面的参数重新赋值分类初始变量
    const options = getCurrentPage().options;
    options.id && (categoryState.value.categoryId = Number(options.id));
    options.pid && (categoryState.value.categoryParentId = Number(options.pid));
    options.page && (categoryState.value.page = Number(options.page));
    options.size && (categoryState.value.size = Number(options.size));
    await sendRequest();
  }

  async function change(_categoryState: Partial<CategoryState>) {
    // 切换分类重置为第一页和请求新的分类数据
    end.value = false;
    categoryState.value.page = 1;

    // 切换分类相同的属性覆盖值
    categoryState.value= {
      ...categoryState.value,
      ..._categoryState,
    };

    // 跳转页面
    _href();

    // 请求课程列表数据
    await sendRequest();
  }

  async function sendRequest(nextPage?: boolean) {
    // 如果接口没有更多数据，滑动底部不再请求
    if (end.value) return;

    // 判断是滑动请求，页数则加1
    nextPage && (categoryState.value.page = categoryState.value.page + 1);

    const data = (
      await queryProductById({
        ...categoryState.value,
        categoryId:
          categoryState.value.categoryId && categoryState.value.categoryId !== -1
            ? categoryState.value.categoryId
            : undefined,
        categoryParentId:
          categoryState.value.categoryParentId &&
          categoryState.value.categoryParentId !== -1
            ? categoryState.value.categoryParentId
            : undefined,
      })
    ).data.current_data;

    // 如果接口最后页的数据长度少了12，则无更多数据
    if (data.length < 12) end.value = true;

    // 判断是否滑动请求更多，是则和之前请求数据组合
    products.value = nextPage ? [...products.value, ...data] : data;
  }

  // 跳转当前页面，携带参数
  function _href() {
    // 跳转页面，{ isHistory: true } 更新当前url
    delayNavigateTo(
      `${getCurrentPage().path}?pid=${categoryState.value.categoryParentId}&id=${
        categoryState.value.categoryId
      }`,
      { isHistory: true }
    );
  }

  return ({
    end,
    products,
    categoryState,
    init,
    change,
    sendRequest,
  });
});

